from flask import Flask, request, render_template
from flask_uuid import FlaskUUID

from entity.models import db
from util.InitConfig import init_website_app_config, init_register_blue_point
from util.LoginUtil import get_login_info, valid_login
from util.WebUtil import get_host, get_port

# define app
app = Flask(__name__, static_folder='static', static_url_path='')
# init app config
init_website_app_config(app)
init_register_blue_point(app)
FlaskUUID(app)
with app.app_context():
    db.init_app(app)
    db.create_all()


@app.before_request
def before():
    url = request.path
    login_info = get_login_info()
    if check_url(url):
        pass
    elif login_info != {}:
        if valid_login(login_info):
            pass
        else:
            return render_template('/common/login.html')
    else:
        return render_template("/common/login.html")


def check_url(url):
    return url.startswith('/view') \
           or url.startswith('/api/login') \
           or url.find(".css") != -1 \
           or url.find(".js") != -1 \
           or url.find(".png") != -1 \
           or url.find(".jpg") != -1 \
           or url.find(".gif") != -1 \
           or url.find("/api/deploy/hook") != -1 \
           or url == '/' \
           or url.find(".woff") != -1 \
           or url.find(".tff") != -1 \
           or url.find(".ico") != -1 \
           or url.find("/api/contact/comment") != -1 \
           or url.find("/api/article/comment") != -1


@app.after_request
def after(environ):
    if request.path != "/login":
        print("user visit path:", request.path)
    return environ


@app.errorhandler(404)
def handle404(error):
    accept = request.headers.get("accept")
    if accept and accept.startswith('application/json'):
        print("ajax")
        return '404', 404
    else:
        return render_template('public/style1/404.html'), 404


@app.errorhandler(500)
def handle500(error):
    accept = request.headers.get("accept")
    if accept and accept.startswith('application/json'):
        return '500', 500
    else:
        return '500 get', 500


@app.teardown_appcontext
def shutdown_session(exception=None):
    db.session.remove()


@app.route("/favicon.ico")
def favicon():
    filename = "public/{}/favicon.ico".format("style1")
    return app.send_static_file(filename)


if __name__ == '__main__':
    app.run(host=get_host(app), port=get_port(app), debug=True)
